using AutoMapper;
using BaseData.Domain;
using BaseData.WriteApi.Appcontext.Command.EweHistoryRecord_Files;
using MediatR;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace BaseData.WriteApi.Appcontext.CommandHandler.EweHistoryRecord_Files
{
    /// <summary>
    /// 更新种母历史记录命令处理器
    /// </summary>
    public class UpdateEweHistoryRecordCommandHandler : IRequestHandler<UpdateEweHistoryRecordCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<EweHistoryRecord> _eweHistoryRecordRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateEweHistoryRecordCommandHandler> _logger;

        public UpdateEweHistoryRecordCommandHandler(
            IBaseRepository<EweHistoryRecord> eweHistoryRecordRepository,
            IMapper mapper,
            ILogger<UpdateEweHistoryRecordCommandHandler> logger)
        {
            _eweHistoryRecordRepository = eweHistoryRecordRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理更新种母历史记录命令
        /// </summary>
        /// <param name="request">更新命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        public async Task<ApiResult<bool>> Handle(UpdateEweHistoryRecordCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证请求参数
                if (request == null)
                {
                    _logger.LogWarning("更新种母历史记录请求参数为空");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "请求参数不能为空", data = false };
                }

                // 验证数据
                if (!request.Validate(out string errorMessage))
                {
                    _logger.LogWarning($"更新种母历史记录数据验证失败: {errorMessage}");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = errorMessage, data = false };
                }

                // 根据ID查询种母历史记录
                var eweHistoryRecord = await _eweHistoryRecordRepository.GetByIdAsync(request.HistoryId);
                
                if (eweHistoryRecord == null)
                {
                    _logger.LogWarning($"未找到ID为 {request.HistoryId} 的种母历史记录");
                    return new ApiResult<bool> { Code = ApiEnum.查询失败, Message = "未找到指定的种母历史记录", data = false };
                }

                // 检查是否已被删除
                if (eweHistoryRecord.IsDeleted)
                {
                    _logger.LogWarning($"ID为 {request.HistoryId} 的种母历史记录已被删除");
                    return new ApiResult<bool> { Code = ApiEnum.查询失败, Message = "种母历史记录已被删除", data = false };
                }

                // 更新实体
                eweHistoryRecord.EweId = request.EweId;
                eweHistoryRecord.MatingDate = request.MatingDate;
                eweHistoryRecord.RamId = request.RamId;
                eweHistoryRecord.PregnancyCheckDate = request.PregnancyCheckDate;
                eweHistoryRecord.PregnancyResult = request.PregnancyResult;
                eweHistoryRecord.DeliveryDate = request.DeliveryDate;
                eweHistoryRecord.HealthyLambCount = request.HealthyLambCount;
                eweHistoryRecord.HealthyLambTotalWeight = request.HealthyLambTotalWeight;
                eweHistoryRecord.WeakLambCount = request.WeakLambCount;
                eweHistoryRecord.DeformedCount = request.DeformedCount;
                eweHistoryRecord.StillbirthCount = request.StillbirthCount;
                eweHistoryRecord.MummyCount = request.MummyCount;
                eweHistoryRecord.AbnormalCount = request.AbnormalCount;
                eweHistoryRecord.CurrentParity = request.CurrentParity;
                eweHistoryRecord.Note = request.Note;

                // 保存到数据库
                var result = await _eweHistoryRecordRepository.UpdateAsync(eweHistoryRecord);
                
                if (result > 0)
                {
                    _logger.LogInformation($"成功更新种母历史记录，ID: {request.HistoryId}");
                    return new ApiResult<bool> { Code = ApiEnum.更新成功, Message = "种母历史记录更新成功", data = true };
                }
                else
                {
                    _logger.LogError($"更新种母历史记录失败，ID: {request.HistoryId}");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "种母历史记录更新失败", data = false };
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning($"参数验证异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = ex.Message, data = false };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新种母历史记录时发生系统异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "系统异常，请联系管理员", data = false };
            }
        }
    }
}